package com.lou.springboot.controller.admin;

import com.lou.springboot.common.ResultVO;
import com.lou.springboot.common.ResultVOUtil;
import com.lou.springboot.entity.Tag;
import com.lou.springboot.enums.ResultEnum;
import com.lou.springboot.service.BlogTagService;
import com.lou.springboot.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RequestMapping("/admin")
@Controller
public class TagController {

    @Autowired
    private BlogTagService tagService;

    @GetMapping("/tags")
    public String tagPage(HttpServletRequest request){
        request.setAttribute("path","tags");
        return "admin/tag";
    }

    @GetMapping("/tags/list")
    @ResponseBody
    public ResultVO list(@RequestParam Map<String,Object> params){
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))){
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        PageUtil pageUtil = new PageUtil(params);
        return ResultVOUtil.success(tagService.getTagsList(pageUtil));
    }

    @PostMapping("/tags/save")
    @ResponseBody
    public ResultVO save(@RequestParam("tagName") String tagName){
        if (StringUtils.isEmpty(tagName)){
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        if (tagService.saveTag(tagName)){
            return ResultVOUtil.success();
        } else{
            return ResultVOUtil.error(ResultEnum.TAG_NAME_REPEAT);
        }
    }

    @PutMapping("/tags/delete")
    @ResponseBody
    public ResultVO delete(@RequestBody Integer[] ids){
        if (ids.length < 1){
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        if (tagService.deleteBatchTag(ids)){
            return ResultVOUtil.success();
        } else {
            return ResultVOUtil.error(ResultEnum.DELETE_FAILED);
        }
    }

    @GetMapping("/tags/info/{tagId}")
    @ResponseBody
    public ResultVO info(@PathVariable Integer tagId){
        if (tagId != null || tagId < 1){
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        Tag tag = tagService.getTagById(tagId);
        if (tag == null){
            return ResultVOUtil.error(ResultEnum.NOT_FOUND);
        } else {
            return ResultVOUtil.success(tag);
        }
    }
}
